package com.atguigu.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;

//客户端一直监听服务器端的上下线
public class ZKClient {

    private static ZooKeeper zk;

    public static void main(String[] args) {
        //1.获取zk连接对象
        try {
            String connect = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
            zk = new ZooKeeper(connect, 4000, new Watcher() {
                public void process(WatchedEvent event) {
                    //该线程不处理变化
                }
            });
            //2.判断父节点存不存在
            Stat exists = zk.exists("/xiyouji", false);
            if(exists ==null){
                zk.create("/xiyouji","".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            }

            //3.监听子节点变化
            register();
            //4.保证客户端一直监听
            Thread.sleep(Long.MAX_VALUE);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zk!=null) {
                    zk.close();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //关闭资源

    }
    public static void register() throws KeeperException, InterruptedException {
        //3.监听子节点变化
        List<String> children = zk.getChildren("/xiyouji", new Watcher() {
            public void process(WatchedEvent event) {
                //当子节点变化,说明服务器上下线了,重新注册监听
                try {
                    register();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        for (String child : children) {
            System.out.println(child);
        }
    }
}
